package org.misalen.web.server.filter;

import java.io.IOException;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.misalen.web.server.config.Uncertain;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 过滤
 * 
 * @author guochao
 *
 */
public class ShiroFilter implements Filter {
	ObjectMapper mapper = new ObjectMapper();
	private static final Logger logger = Logger.getLogger(ShiroFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 检测不过滤地址
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String url = httpRequest.getRequestURI();
		for (String u : Uncertain.notFilter) {
			if (url.indexOf(u) >= 0) {
				chain.doFilter(request, response);
				return;
			}
		}
		String version = httpRequest.getHeader("version");
		if (version != null && version.equals("test")) {
			chain.doFilter(request, response);
			return;
		}
		if (httpRequest.getMethod().equals("GET")) {
			chain.doFilter(request, response);
			return;
		}
		ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper(httpRequest);
		chain.doFilter(dealWithParameter(requestWrapper), response);

	}

	@Override
	public void destroy() {

	}

	/**
	 * 处理参数
	 * 
	 * @param request
	 * @return
	 */
	private ParameterRequestWrapper dealWithParameter(ParameterRequestWrapper request) {
		String dataString = request.getInputString();
		String url = request.getRequestURI();
		logger.info("### 请求地址 -----" + url);
		logger.info("### 请求串 -----" + dataString);
		JSONObject object = JSONObject.parseObject(dataString);
		JSONObject filter = object.getJSONObject("filter");
		JSONObject data = object.getJSONObject("data");
		Set<String> datas = filter.keySet();
		request.setParameter("servletPath", request.getRequestURI());
		for (String str : datas) {
			request.setParameter(str, filter.get(str));
		}
		if (data != null) {
			request.setInputStream(data.toString());
		} else {
			request.setInputStream(null);
		}
		return request;
	}

}
